import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
from datetime import datetime
import pyttsx3
import threading
from utils import get_essay_from_api, analyze_sentence, save_api_key, load_api_key
from recite_mode import ReciteMode

class EssayApp:
    def __init__(self, root):
        self.root = root
        self.root.title("英语作文背诵程序")
        self.root.geometry("900x600")
        
        # 设置主题色
        self.primary_color = "#0078D4"  # Windows 10 主题色
        self.bg_color = "#FFFFFF"
        self.text_color = "#333333"
        
        # 配置样式
        self.configure_styles()
        
        # 创建数据目录
        self.data_dir = "data"
        if not os.path.exists(self.data_dir):
            os.makedirs(self.data_dir)
            
        # 初始化语音引擎
        self.engine = pyttsx3.init()
        
        # 创建主界面
        self.create_main_interface()
        
        # 创建右键菜单
        self.create_context_menu()
        
    def configure_styles(self):
        # 配置主题
        style = ttk.Style()
        style.theme_use('default')
        
        # 配置按钮样式
        style.configure('Primary.TButton',
                      background=self.primary_color,
                      foreground='white',
                      padding=10,
                      font=('Microsoft YaHei UI', 10))
        
        # 配置标签样式
        style.configure('Title.TLabel',
                      font=('Microsoft YaHei UI', 16, 'bold'),
                      foreground=self.text_color)
        
        style.configure('Subtitle.TLabel',
                      font=('Microsoft YaHei UI', 12),
                      foreground=self.text_color)
        
        # 配置Treeview样式
        style.configure('Treeview',
                      font=('Microsoft YaHei UI', 10),
                      background=self.bg_color,
                      foreground=self.text_color,
                      rowheight=30)
        
        style.configure('Treeview.Heading',
                      font=('Microsoft YaHei UI', 10, 'bold'),
                      background=self.primary_color,
                      foreground='white')
        
    def create_main_interface(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建标题
        title_frame = ttk.Frame(main_frame)
        title_frame.pack(fill=tk.X, pady=(0, 20))
        
        ttk.Label(title_frame,
                 text="英语作文背诵",
                 style='Title.TLabel').pack(side=tk.LEFT)
        
        # 创建按钮框架
        button_frame = ttk.Frame(title_frame)
        button_frame.pack(side=tk.RIGHT)
        
        # 创建新建作文按钮
        new_btn = ttk.Button(button_frame,
                           text="新建作文",
                           command=self.create_new_essay,
                           style='Primary.TButton')
        new_btn.pack(side=tk.LEFT, padx=5)
        
        # 创建设置按钮
        settings_btn = ttk.Button(button_frame,
                                text="设置",
                                command=self.show_settings,
                                style='Primary.TButton')
        settings_btn.pack(side=tk.LEFT, padx=5)
        
        # 创建作文列表框架
        list_frame = ttk.Frame(main_frame)
        list_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建列表标题
        ttk.Label(list_frame,
                 text="我的作文",
                 style='Subtitle.TLabel').pack(anchor=tk.W, pady=(0, 10))
        
        # 创建作文列表
        self.essay_list = ttk.Treeview(list_frame,
                                     columns=("title", "date"),
                                     show="headings",
                                     style='Treeview')
        self.essay_list.heading("title", text="标题")
        self.essay_list.heading("date", text="创建日期")
        self.essay_list.pack(fill=tk.BOTH, expand=True)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame,
                                orient=tk.VERTICAL,
                                command=self.essay_list.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.essay_list.configure(yscrollcommand=scrollbar.set)
        
        # 添加双击事件
        self.essay_list.bind("<Double-1>", self.start_recite_mode)
        
        # 加载已有作文
        self.load_essays()
        
    def create_context_menu(self):
        # 创建右键菜单
        self.context_menu = tk.Menu(self.root, tearoff=0)
        self.context_menu.add_command(label="编辑", command=self.edit_essay)
        self.context_menu.add_command(label="删除", command=self.delete_essay)
        self.context_menu.add_separator()
        self.context_menu.add_command(label="背诵", command=self.start_recite_mode)
        
        # 绑定右键事件
        self.essay_list.bind("<Button-3>", self.show_context_menu)
        
    def show_context_menu(self, event):
        # 获取点击位置的项目
        item = self.essay_list.identify_row(event.y)
        if item:
            # 选中该项目
            self.essay_list.selection_set(item)
            # 显示菜单
            self.context_menu.post(event.x_root, event.y_root)
            
    def edit_essay(self):
        # 获取选中的作文
        selection = self.essay_list.selection()
        if not selection:
            return
            
        item = self.essay_list.item(selection[0])
        title = item["values"][0]
        
        # 加载作文数据
        filename = f"{title.replace(' ', '_')}.json"
        with open(os.path.join(self.data_dir, filename), "r", encoding="utf-8") as f:
            essay_data = json.load(f)
            
        # 创建编辑窗口
        self.edit_dialog = tk.Toplevel(self.root)
        self.edit_dialog.title("编辑作文")
        self.edit_dialog.geometry("800x600")
        
        # 设置窗口样式
        self.edit_dialog.configure(bg=self.bg_color)
        
        # 创建主框架
        main_frame = ttk.Frame(self.edit_dialog, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建标题
        ttk.Label(main_frame,
                 text="编辑作文",
                 style='Title.TLabel').pack(anchor=tk.W, pady=(0, 20))
        
        # 创建输入框
        ttk.Label(main_frame,
                 text="作文题目：",
                 style='Subtitle.TLabel').pack(anchor=tk.W, pady=10)
        
        title_entry = ttk.Entry(main_frame,
                              width=40,
                              font=('Microsoft YaHei UI', 10))
        title_entry.pack(fill=tk.X, pady=5)
        title_entry.insert(0, title)
        
        # 创建英文编辑框
        ttk.Label(main_frame,
                 text="英文内容：",
                 style='Subtitle.TLabel').pack(anchor=tk.W, pady=10)
        
        english_text = tk.Text(main_frame,
                             font=('Microsoft YaHei UI', 12),
                             height=10)
        english_text.pack(fill=tk.BOTH, expand=True, pady=5)
        english_text.insert("1.0", essay_data["content"]["english"])
        
        # 创建中文编辑框
        ttk.Label(main_frame,
                 text="中文翻译：",
                 style='Subtitle.TLabel').pack(anchor=tk.W, pady=10)
        
        chinese_text = tk.Text(main_frame,
                             font=('Microsoft YaHei UI', 12),
                             height=10)
        chinese_text.pack(fill=tk.BOTH, expand=True, pady=5)
        chinese_text.insert("1.0", essay_data["content"]["chinese"])
        
        def save_edit():
            new_title = title_entry.get().strip()
            if not new_title:
                messagebox.showerror("错误", "请输入作文题目")
                return
                
            # 更新作文数据
            essay_data["title"] = new_title
            essay_data["content"]["english"] = english_text.get("1.0", tk.END).strip()
            essay_data["content"]["chinese"] = chinese_text.get("1.0", tk.END).strip()
            
            # 保存文件
            if new_title != title:
                # 如果标题改变，删除旧文件
                os.remove(os.path.join(self.data_dir, filename))
                filename = f"{new_title.replace(' ', '_')}.json"
                
            with open(os.path.join(self.data_dir, filename), "w", encoding="utf-8") as f:
                json.dump(essay_data, f, ensure_ascii=False, indent=2)
                
            # 更新列表
            self.load_essays()
            self.edit_dialog.destroy()
            
        # 创建保存按钮
        ttk.Button(main_frame,
                  text="保存修改",
                  command=save_edit,
                  style='Primary.TButton').pack(pady=20)
        
    def delete_essay(self):
        # 获取选中的作文
        selection = self.essay_list.selection()
        if not selection:
            return
            
        item = self.essay_list.item(selection[0])
        title = item["values"][0]
        
        # 确认删除
        if messagebox.askyesno("确认删除", f"确定要删除作文《{title}》吗？"):
            # 删除文件
            filename = f"{title.replace(' ', '_')}.json"
            os.remove(os.path.join(self.data_dir, filename))
            
            # 更新列表
            self.load_essays()
            
    def show_settings(self):
        """显示设置界面"""
        # 创建设置窗口
        settings_window = tk.Toplevel(self.root)
        settings_window.title("设置")
        settings_window.geometry("400x300")
        
        # 创建主框架
        main_frame = ttk.Frame(settings_window, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建标题
        ttk.Label(main_frame,
                 text="设置",
                 style='Title.TLabel').pack(anchor=tk.W, pady=(0, 20))
        
        # 创建API密钥输入框架
        api_frame = ttk.Frame(main_frame)
        api_frame.pack(fill=tk.X, pady=10)
        
        ttk.Label(api_frame,
                 text="DeepSeek API密钥：",
                 style='Subtitle.TLabel').pack(side=tk.LEFT)
        
        api_key_var = tk.StringVar(value=load_api_key() or "")
        api_entry = ttk.Entry(api_frame, textvariable=api_key_var, show="*")
        api_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(10, 0))
        
        # 创建按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=20)
        
        def save_settings():
            """保存设置"""
            api_key = api_key_var.get().strip()
            if api_key:
                save_api_key(api_key)
                messagebox.showinfo("成功", "设置已保存")
                settings_window.destroy()
            else:
                messagebox.showerror("错误", "API密钥不能为空")
        
        def cancel():
            """取消设置"""
            settings_window.destroy()
        
        # 创建取消按钮
        ttk.Button(button_frame,
                  text="取消",
                  command=cancel,
                  style='Secondary.TButton').pack(side=tk.LEFT, padx=5)
        
        # 创建保存按钮
        ttk.Button(button_frame,
                  text="保存",
                  command=save_settings,
                  style='Primary.TButton').pack(side=tk.RIGHT, padx=5)
        
    def load_essays(self):
        # 清空列表
        for item in self.essay_list.get_children():
            self.essay_list.delete(item)
            
        # 加载作文
        essays = []
        for filename in os.listdir(self.data_dir):
            if filename.endswith(".json"):
                try:
                    with open(os.path.join(self.data_dir, filename), "r", encoding="utf-8") as f:
                        essay = json.load(f)
                        
                        # 验证并设置默认值
                        if not isinstance(essay, dict):
                            continue
                            
                        # 确保有title字段，否则使用文件名
                        if "title" not in essay:
                            essay["title"] = os.path.splitext(filename)[0].replace("_", " ")
                            
                        # 确保有date字段，否则使用当前日期
                        if "date" not in essay:
                            essay["date"] = datetime.now().strftime("%Y-%m-%d")
                            
                        essays.append(essay)
                except (json.JSONDecodeError, IOError) as e:
                    print(f"Error loading {filename}: {e}")
                    continue
                    
        # 按日期排序
        try:
            essays.sort(key=lambda x: datetime.strptime(x["date"], "%Y-%m-%d"))
        except (KeyError, ValueError) as e:
            print(f"Error sorting essays: {e}")
        
        # 添加到列表
        for essay in essays:
            self.essay_list.insert("", "end", values=(essay["title"], essay.get("date", "Unknown")))
            
    def create_new_essay(self):
        """创建新作文"""
        # 创建新窗口
        new_window = tk.Toplevel(self.root)
        new_window.title("创建新作文")
        new_window.geometry("600x400")
        
        # 设置窗口样式
        new_window.configure(bg=self.bg_color)
        
        # 创建主框架
        main_frame = ttk.Frame(new_window, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建标题
        ttk.Label(main_frame,
                 text="创建新作文",
                 style='Title.TLabel').pack(anchor=tk.W, pady=(0, 20))
        
        # 创建输入框架
        input_frame = ttk.Frame(main_frame)
        input_frame.pack(fill=tk.X, pady=10)
        
        ttk.Label(input_frame,
                 text="作文题目：",
                 style='Subtitle.TLabel').pack(side=tk.LEFT)
        
        title_entry = ttk.Entry(input_frame, width=40)
        title_entry.pack(side=tk.LEFT, padx=10)
        
        # 创建进度条
        progress_frame = ttk.Frame(main_frame)
        progress_frame.pack(fill=tk.X, pady=10)
        
        progress_var = tk.DoubleVar()
        progress_bar = ttk.Progressbar(
            progress_frame,
            variable=progress_var,
            maximum=1.0,
            mode='determinate'
        )
        progress_bar.pack(fill=tk.X)
        
        # 创建状态标签
        status_label = ttk.Label(
            progress_frame,
            text="准备生成...",
            style='Subtitle.TLabel'
        )
        status_label.pack(pady=5)
        
        def update_progress(progress):
            progress_var.set(progress)
            status_label.config(text=f"生成进度：{int(progress * 100)}%")
            new_window.update()
        
        def generate_essay():
            title = title_entry.get().strip()
            if not title:
                messagebox.showerror("错误", "请输入作文题目")
                return
                
            try:
                # 禁用生成按钮
                generate_btn.config(state=tk.DISABLED)
                status_label.config(text="正在生成作文...")
                
                # 调用API生成作文
                essay_data = get_essay_from_api(title, progress_callback=update_progress)
                
                # 保存作文
                self.save_essay(title, essay_data)
                
                # 更新列表
                self.load_essays()
                
                # 关闭窗口
                new_window.destroy()
                
                # 显示成功消息
                messagebox.showinfo("成功", "作文生成成功！")
                
            except Exception as e:
                messagebox.showerror("错误", f"生成作文时发生错误：{str(e)}")
                generate_btn.config(state=tk.NORMAL)
                status_label.config(text="生成失败，请重试")
        
        # 创建按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(pady=20)
        
        generate_btn = ttk.Button(button_frame,
                  text="生成",
                  command=generate_essay,
                  style='Primary.TButton')
        generate_btn.pack(side=tk.LEFT, padx=5)
        
        ttk.Button(button_frame,
                  text="取消",
                  command=new_window.destroy,
                  style='Primary.TButton').pack(side=tk.LEFT, padx=5)
        
    def save_essay(self, title, content):
        essay_data = {
            "title": title,
            "date": datetime.now().strftime("%Y-%m-%d"),
            "content": content
        }
        
        filename = f"{title.replace(' ', '_')}.json"
        with open(os.path.join(self.data_dir, filename), "w", encoding="utf-8") as f:
            json.dump(essay_data, f, ensure_ascii=False, indent=2)
            
    def start_recite_mode(self, event=None):
        # 获取选中的作文
        selection = self.essay_list.selection()
        if not selection:
            return
            
        item = self.essay_list.item(selection[0])
        title = item["values"][0]
        
        # 加载作文数据
        filename = f"{title.replace(' ', '_')}.json"
        with open(os.path.join(self.data_dir, filename), "r", encoding="utf-8") as f:
            essay_data = json.load(f)
            
        # 创建背诵模式窗口
        recite_window = tk.Toplevel(self.root)
        recite_window.title(f"背诵模式 - {title}")
        recite_window.geometry("800x600")
        
        # 启动背诵模式
        ReciteMode(recite_window, essay_data["content"])

if __name__ == "__main__":
    root = tk.Tk()
    app = EssayApp(root)
    root.mainloop()